/*
 * @Descripttion: 
 * @version: 
 * @Author: sueRimn
 * @Date: 2021-03-09 17:12:47
 * @LastEditors: wenbin
 * @LastEditTime: 2021-08-19 12:38:16
 */
import axios from 'axios';
import catchUtil from '../utils/catch'
import magusApi from './config'
// import {
//   Message
// } from 'element-ui';
// 创建axios实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 300000,
})

console.log(service);

//设置cookie
var setCookie = function (cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

//清除cookie  
var clearCookie = function (name) {  
  setCookie(name, "", -1);  
}

let pendingQueue = new Map()
let CancelToken = axios.CancelToken

// 判断请求是否在队列中，如果在就对队列中的该请求执行取消操作
const judgePendingFunc = function(config) {
  if (pendingQueue.has(`${config.method}->${config.url}`)) {
    pendingQueue.get(`${config.method}->${config.url}`)() //注意这里的括号不要漏掉
  }
}
// 删除队列中对应已执行的请求
const removeResolvedFunc = function(config) {
  if (pendingQueue.has(`${config.method}->${config.url}`)) {
    pendingQueue.delete(`${config.method}->${config.url}`)
  }
}

var resetSetItem = function (key, newVal) {
  if (key === 'taskChange') {

      // 创建一个StorageEvent事件
      var newStorageEvent = document.createEvent('StorageEvent');
      const storage = {
          setTaskItem: function (k, val) {
              sessionStorage.setItem(k, val);

              // 初始化创建的事件
              newStorageEvent.initStorageEvent('setTaskItem', false, false, k, null, val, null, null);

              // 派发对象
              window.dispatchEvent(newStorageEvent)
          }
      }
      return storage.setTaskItem(key, newVal);
  }
}

// 202 头部信息
let MlinkUrl = ''

// request拦截器
service.interceptors.request.use(
  config => {
    // 请求发起之前先检验该请求是否在队列中，如果在就把队列中pending的请求cancel掉
    judgePendingFunc(config)
    // 将pending队列中的请求设置为当前
    config.cancelToken = new CancelToken(cb => {
      pendingQueue.set(`${config.method}->${config.url}`, cb)
    })

    let _token = catchUtil.getLocalItem('token');
    if (_token) {
      config.headers['Authorization'] = 'Bearer '+ _token; // 让每个请求携带自定义token 请根据实际情况自行修改 // change by wen hao
      config.headers['Content-Type'] = 'application/json';
    }
    if (config.headers['Mlink-URL']) {
      MlinkUrl = config.headers['Mlink-URL']
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    removeResolvedFunc(response.config)
    const res = response.data;
    // 202 状态码拦截
    if (response.status === 202) {
      let mlinkData = {};
      let mlinkDataLocal = catchUtil.getLocalItem('mlinkData');
      if (mlinkDataLocal) {
        mlinkData = JSON.parse(mlinkDataLocal)
      }
      if (mlinkData[res.taskId]) {
        mlinkData[res.taskId] = Object.assign(mlinkData[res.taskId], res);
      } else {
        mlinkData[res.taskId] = res
      }
      
      if (!document.getElementById(res.taskId) && !mlinkData[res.taskId].code) {
        mlinkData[res.taskId].elMessage = document.createElement("div");
        mlinkData[res.taskId].elMessage.id = res.taskId
        var innerHtml = `
            <div class="el-dialog__wrapper" style="z-index: 2001;">
            <div role="dialog" aria-modal="true" aria-label="请稍后" class="el-dialog" style="margin-top: 15vh; width: 30%;">
              <div class="el-dialog__header" style="cursor: move;">
                <span class="el-dialog__title">请稍后</span>
              </div>
              <div class="el-dialog__body">
                <div class="dialog-content" style="padding: 15px;" id="dialog_${res.taskId}">
                </div>
              </div>
              <div class="el-dialog__footer">
                <span class="dialog-footer" id="dialog-footer-${res.taskId}">
                  
                </span>
              </div>
            </div>
          </div>
          <div class="v-modal" tabindex="0" style="z-index: 2000;"></div>
        `
        mlinkData[res.taskId].elMessage.innerHTML = innerHtml;
        document.body.appendChild(mlinkData[res.taskId].elMessage)
      }

      if (document.getElementById(`dialog_${res.taskId}`)) {
        let htmls = `
          <div style="display: ${res.progress ? 'block' : 'none'}; margin-bottom: 15px;" role="progressbar" aria-valuenow="${res.progress}" aria-valuemin="0" aria-valuemax="100" class="el-progress el-progress--line el-progress--text-inside">
            <div class="el-progress-bar">
              <div class="el-progress-bar__outer" style="height: 15px;">
                <div class="el-progress-bar__inner" style="width: ${res.progress}%;">
                  <div class="el-progress-bar__innerText">${res.progress}%</div>
                </div>
              </div>
            </div>
          </div>
          <div>${res.msg ? res.msg : '请稍后。。。。'}</div>
        `
        document.getElementById(`dialog_${res.taskId}`).innerHTML = htmls
      }

      if (document.getElementById(`dialog-footer-${res.taskId}`)) {
        let htmls = `
          <button type="button" id="button-continue-${res.taskId}" class="el-button el-button--default el-button--mini">
            <span>继续等待</span>
          </button>
          <button type="button" id="button-background-${res.taskId}" class="el-button el-button--primary el-button--mini">
            <span>后台等待</span>
          </button>
        `
        document.getElementById(`dialog-footer-${res.taskId}`).innerHTML = htmls;
        document.getElementById(`button-background-${res.taskId}`).onclick = function () {
          if (document.getElementById(res.taskId)) {
            document.getElementById(res.taskId).style.display = "none";
          }
          clearTimeout(mlinkData[res.taskId].timer);
        }
      }
      
      mlinkData[res.taskId].code = response.status
      mlinkData[res.taskId].MlinkUrl = MlinkUrl
      
      mlinkData[res.taskId].timer = setTimeout(() => {
        magusApi.get(res.url, {}, {"Mlink-URL": MlinkUrl})
      }, 3000)
      catchUtil.setLocalItem('mlinkData', JSON.stringify(mlinkData))
      resetSetItem("taskChange", JSON.stringify(mlinkData))
    }

    // 成功状态并且有任务ID
    if (response.status === 200 && res.taskId) {
      let mlinkDataLocal = catchUtil.getLocalItem('mlinkData');
      if (mlinkDataLocal) {
        let mlinkData = JSON.parse(mlinkDataLocal);
        // if (document.getElementById(res.taskId)) {
        //   document.getElementById(res.taskId).remove();
        // }
        if (document.getElementById(`dialog_${res.taskId}`)) {
          let htmls = `
            <div style="display: ${res.progress ? 'block' : 'none'}" role="progressbar" aria-valuenow="${res.progress}" aria-valuemin="0" aria-valuemax="100" class="el-progress el-progress--line el-progress--text-inside">
              <div class="el-progress-bar">
                <div class="el-progress-bar__outer" style="height: 15px;">
                  <div class="el-progress-bar__inner" style="width: ${res.progress}%;">
                    <div class="el-progress-bar__innerText">${res.progress}%</div>
                  </div>
                </div>
              </div>
            </div>
            <div style="margin-top: 15px;" style="padding: 10px;">${res.msg ? res.msg : '请稍后。。。。'}</div>
          `
          document.getElementById(`dialog_${res.taskId}`).innerHTML = htmls
        }

        if (document.getElementById(`dialog-footer-${res.taskId}`)) {
          let htmls = `
            <button type="button" id="button-close-${res.taskId}" class="el-button el-button--default el-button--mini">
              <span>确定</span>
            </button>
          `
          document.getElementById(`dialog-footer-${res.taskId}`).innerHTML = htmls;
          document.getElementById(`button-close-${res.taskId}`).onclick = function () {
            if (document.getElementById(res.taskId)) {
              document.getElementById(res.taskId).remove();
            }
          }
        }

        if (document.getElementById(res.taskId) && document.getElementById(res.taskId).style.display === 'none') {
          document.getElementById(res.taskId).remove();
        }
        
        if (mlinkData[res.taskId] && mlinkData[res.taskId].timer) {
          clearTimeout(mlinkData[res.taskId].timer);
          mlinkData[res.taskId] = res
          mlinkData[res.taskId].code = response.status
          mlinkData[res.taskId].MlinkUrl = MlinkUrl
          // delete mlinkData[res.taskId]
          catchUtil.setLocalItem('mlinkData', JSON.stringify(mlinkData))
          resetSetItem("taskChange", JSON.stringify(mlinkData))
        }
      }
    }

    return res;
  },
  error => {
    if (error.response) {
      var elMessage = document.createElement("div");
      elMessage.className = "el-message el-message--error";
      elMessage.style = "z-index: 3000;";
      var elMessageInner = `<i class="el-message__icon el-icon-error"></i><p class="el-message__content">${error.response.data.error}</p>`;
      elMessage.innerHTML = elMessageInner;
      document.body.appendChild(elMessage);
      setTimeout(() => {
        elMessage.remove();
      }, 3000);
      if (error.response.status === 401) {
        setTimeout(() => {
          let url = window.location.origin;
          localStorage.clear();
          clearCookie('auth_token')
          window.open(url, '_self')
        }, 2000)
      }
    }
    return Promise.reject(error);
  }
);

export default service;